package me.leiusual.sharing

import android.content.Context
import android.util.Log
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.module.AppGlideModule
import com.bumptech.glide.request.RequestOptions
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import timber.log.Timber
import java.io.InputStream
import java.util.concurrent.TimeUnit

/**
 * Create by leiusual on 2018/7/15
 */
@GlideModule
class SharingGlideModule : AppGlideModule() {

  override fun applyOptions(context: Context, builder: GlideBuilder) {

    // 请求配置
    val options = RequestOptions()
        .encodeQuality(60)
        .format(DecodeFormat.PREFER_RGB_565)
        .transform(CenterCrop())

    // 设置
    builder.setLogLevel(Log.VERBOSE)
        .setLogRequestOrigins(true)
        .setDefaultRequestOptions(options)
  }

  override fun registerComponents(context: Context, glide: Glide, registry: Registry) {

    // 接口日志
    val httpLoggingInterceptor = HttpLoggingInterceptor { Timber.d(it) }
    httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BASIC

    // 客户端
    val okHttpClient = OkHttpClient.Builder()
        .callTimeout(30, TimeUnit.SECONDS)
        .addNetworkInterceptor(httpLoggingInterceptor)
        .build()

    // 替换OkHttpClient
    val factory = OkHttpUrlLoader.Factory(okHttpClient)
    registry.replace(GlideUrl::class.java, InputStream::class.java, factory)
  }
}